<template>
    <div class="wrapper">
        <t-card>
            <t-row class="table-header">
                <t-space>
                    <t-input v-model="searchKey" placeholder="请输入搜索的姓名或邮箱" size="medium"></t-input>
                    <t-button theme="primary" size="medium" @click="handleSearch">搜索</t-button>
                    <t-button theme="primary" size="medium" @click="showAddDialog">添加</t-button>
                </t-space>
            </t-row>
            <t-table :row-key="rowKey" :data="userListData" :columns="columns" :size="size" :bordered="bordered"
                :stripe="stripe" :resizable="resizable" :loading="loading" :pagination="pagination"
                @page-change="rehandlePageChange" class="table-content">
                <template #is_active="{ row }">
                    <t-switch v-model="row.is_active" :label="['启用', '禁用']"
                        @change="(val: boolean) => handleStatusChange(val, row)" />
                </template>
                <template #options="{ row }">
                    <t-space>
                        <t-button theme="default" size="small" @click="showEditDialog(row)">编辑</t-button>
                        <t-button theme="danger" size="small" @click="handleDelete(row)">删除</t-button>
                        <t-button theme="primary" size="small" @click="handleResetPassword(row)">重置密码</t-button>
                    </t-space>
                </template>
            </t-table>
        </t-card>
        <t-dialog :visible="visibleAdd" header="添加用户" :footer="false" width="400px" @close="visibleAddClose">
            <t-form ref="addFormRef" :data="addForm" :rules="addRules" :label-width="60" class="add-form"
                @submit="handleAddConfirm">
                <t-form-item label="邮箱" name="email">
                    <t-input v-model="addForm.email" placeholder="请输入邮箱" size="medium"></t-input>
                </t-form-item>
                <t-form-item label="角色" name="role">
                    <t-select v-model="addForm.role" placeholder="请选择角色" size="medium">
                        <t-option v-for="item in roleList" :key="item.code" :value="item.code">
                            {{ item.name }}
                        </t-option>
                    </t-select>
                </t-form-item>
                <t-form-item>
                    <t-button type="submit" theme="primary" block>确定</t-button>
                </t-form-item>
            </t-form>
        </t-dialog>
        <t-dialog :visible="visibleEdit" header="编辑用户" :footer="false" width="500px" @close="visibleEditClose">
            <t-form ref="editFormRef" :data="editForm" :rules="editRules" :label-width="60" class="add-form"
                @submit="handleEditConfirm">
                <t-form-item label="邮箱" name="email">
                    <t-input v-model="editForm.email" placeholder="请输入邮箱" size="medium"></t-input>
                </t-form-item>
                <t-form-item label="角色" name="role">
                    <t-select v-model="editForm.role" placeholder="请选择角色" size="medium">
                        <t-option v-for="item in roleList" :key="item.code" :value="item.code">
                            {{ item.name }}
                        </t-option>
                    </t-select>
                </t-form-item>
                <t-form-item>
                    <t-button type="submit" theme="primary" block>确定</t-button>
                </t-form-item>
            </t-form>
        </t-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next';
import type { UserList, addForm, editForm, SubmitParams } from '@/types/interface';
import type { RoleAllList } from '@/api/modules/roleModule';
import { getRoleAll } from '@/api/role';
import { getUserList, addUser, editUser, deleteUser, changeUserStatus } from '@/api/user';
import { resetPassword } from '@/api/login'
import { FormInstanceFunctions } from 'tdesign-vue-next';

import { useUserStore } from '@/store';
const userStore = useUserStore();

// 搜索框
const searchKey = ref('');

// 表格属性
const rowKey = ref('id');
const userListData = ref<UserList[]>([]);
const size = ref('medium');
const bordered = ref(true);
const stripe = ref(true);
const resizable = ref(true);
const loading = ref(false);
const pagination = ref({
    defaultCurrent: 1,
    defaultPageSize: 10,
    total: 0,
    current: 1,
    pageSize: 10,
    pageSizeOptions: [2, 5, 10],
});

// 角色列表
const roleList = ref<RoleAllList[]>([]);

const uid = userStore.id;

// 处理分页变化
const rehandlePageChange = async (curr: any, pageInfo: unknown) => {
    pagination.value.current = curr.current;
    pagination.value.pageSize = curr.pageSize;
    await getUserListData();
};

// 表格列配置
const columns = ref([
    {
        title: '邮箱',
        colKey: 'email',
        align: 'center',
        width: 150,
    },
    {
        title: '姓名',
        colKey: 'name',
        align: 'center',
        width: 80,
    },
    {
        title: '角色',
        colKey: 'role',
        align: 'center',
        width: 80,
    },
    {
        title: '状态',
        colKey: 'is_active',
        align: 'center',
        width: 80,
    },
    {
        title: '创建时间',
        colKey: 'create_time',
        align: 'center',
        width: 140,
    },
    {
        title: '操作',
        colKey: 'options',
        align: 'center',
        width: 170,
    },
]);

const handleStatusChange = async (val: boolean, row: UserList) => {
    try {
        const params = {
            id: row.id,
            is_active: val ? 1 : 0,
            uid: uid,
        }
        const res = await changeUserStatus(params);
        if (res.errcode == 0) {
            getUserListData();
        }
    } catch (error) {
        console.error('请求失败', error);
        row.is_active = !val;
    } finally {
        loading.value = false;
    }
}

// 添加弹窗
const visibleAdd = ref(false);
const addFormRef = ref<FormInstanceFunctions>();
const addForm = ref<addForm>({
    email: '',
    role: '',
});
const addRules = ref({
    email: [
        { required: true, message: '请输入邮箱', type: 'error' },
        { email: true, message: '请输入正确的邮箱格式', type: 'error' }
    ],
    role: [
        { required: true, message: '请选择角色', type: 'error' }
    ],
});
const showAddDialog = () => {
    addFormRef.value?.reset()

    addForm.value.email = "";
    addForm.value.role = "";
    visibleAdd.value = true;
};
const handleAddConfirm = async ({ validateResult, firstError }: SubmitParams) => {
    if (!validateResult) {
        console.error(firstError);
        return;
    }
    try {
        loading.value = true;
        const params = {
            uid: uid,
            email: addForm.value.email,
            role: addForm.value.role,
        }
        const res = await addUser(params);
        if (res.errcode == 0) {
            loading.value = false;
            visibleAdd.value = false;
            MessagePlugin.success(res.message, 1000);
            getUserListData();
        }
    } catch (error) {
        console.error('请求失败', error);
    } finally {
        loading.value = false;
    }
};
const visibleAddClose = () => {
    visibleAdd.value = false;
};

// 编辑弹窗
const visibleEdit = ref(false);
const editFormRef = ref<editForm>({
    id: 0,
    email: '',
    role: '',
});
const editForm = ref<editForm>({
    id: 0,
    email: '',
    role: '',
});
const editRules = ref({
    email: [
        { required: true, message: '请输入邮箱', type: 'error' },
        { email: true, message: '请输入正确的邮箱格式', type: 'error' }
    ],
    role: [
        { required: true, message: '请选择角色', type: 'error' }
    ],
});
const showEditDialog = (row: UserList) => {
    visibleEdit.value = true;
    editForm.value.id = row.id;
    editForm.value.email = row.email;
    editForm.value.role = row.role;
};
const handleEditConfirm = async ({ validateResult, firstError }: SubmitParams) => {
    if (!validateResult) {
        console.error(firstError);
        return;
    }
    try {
        loading.value = true;
        const params = {
            id: editForm.value.id,
            email: editForm.value.email,
            role: editForm.value.role,
            uid: uid,
        }
        const res = await editUser(params);
        if (res.errcode == 0) {

            MessagePlugin.success(res.message, 1000);
            visibleEdit.value = false;
            getUserListData();
        }
    } catch (error) {
        console.error('请求失败', error);
    } finally {
        loading.value = false;
    }
};
const visibleEditClose = () => {
    visibleEdit.value = false;
};

const handleDelete = async (row: UserList) => {
    const params = {
        id: row.id,
        uid: uid,
    }
    loading.value = true;
    const dialog = DialogPlugin.confirm({
        header: '删除用户',
        body: '是否删除该用户，此操作是不可逆的？',
        confirmBtn: '确定',
        cancelBtn: '取消',
        onConfirm: async () => {

            const res = await deleteUser(params);
            if (res.errcode == 0) {
                MessagePlugin.success(res.message, 1000).then(() => {
                    dialog.destroy();
                    pagination.value.current = 1;
                    getUserListData();
                })
            }

        }
    });
    loading.value = false;
}

const handleResetPassword = async (row: UserList) => {
    const params = {
        id: row.id,
        uid: uid,
    }
    loading.value = true;
    const dialog = DialogPlugin.confirm({
        header: '重置密码',
        body: '是否重置该用户密码，此操作是不可逆的？',
        confirmBtn: '确定',
        cancelBtn: '取消',
        onConfirm: async () => {
            const res = await resetPassword(params);
            if (res.errcode == 0) {
                MessagePlugin.success(res.message, 1000).then(() => {
                    dialog.destroy();
                    getUserListData();
                })
            }

        }
    });
    loading.value = false;
}

// 搜索
const handleSearch = () => {
    pagination.value.current = 1;
    getUserListData();
};

// 获取用户列表
const getUserListData = async () => {
    const params = {
        page: pagination.value.current,
        pageSize: pagination.value.pageSize,
        searchKey: searchKey.value,
        uid: uid,
    };
    try {
        loading.value = true;
        const res = await getUserList(params);
        userListData.value = res.data.users;
        pagination.value.total = res.data.total;
        loading.value = false;
    } catch (error) {
        console.error('获取用户列表失败', error);
        // MessagePlugin.error('获取用户列表失败');
    } finally {
        loading.value = false;
    }
};

const getRoleLists = async () => {
    const res = await getRoleAll({});
    roleList.value = res.data;
};

onMounted(() => {
    getUserListData();
    getRoleLists();
});
</script>

<style scoped>
.wrapper {
    padding: 20px;
}

.table-header {
    margin-top: 20px;
    margin-bottom: 20px;
}

.table-content {
    min-width: 840px;
}

.add-form {
    margin-top: 10px;
}
</style>
